const http = require('http');
const WebSocket = require('ws');

// 测试配置
const CONFIG = {
    server: {
        host: 'localhost',
        port: 3000,
        protocol: 'http'
    },
    // 测试用户信息
    testUser: {
        mobile: '17091271111',
        password: '123456',
        passwordHash: 'e10adc3949ba59abbe56e057f20f883e' // 123456的MD5
    },
    // 测试角色信息
    testCharacter: {
        name: '测试角色',
        sex: 1, // 1:男, 0:女
        roleType: 1, // 1:武士, 2:文人, 3:异师
        headIndex: 2
    }
};

// 测试宝石系统功能
class GemSystemTester {
    constructor() {
        this.token = null;
        this.userId = null;
        this.ws = null;
        this.characters = [];
        this.selectedCharacter = null;
        this.testResults = [];
    }

    // HTTP登录
    async httpLogin() {
        console.log('🔐 HTTP登录测试...');

        return new Promise((resolve, reject) => {
            const postData = JSON.stringify({
                mobile: CONFIG.testUser.mobile,
                pwd: CONFIG.testUser.passwordHash
            });

            const options = {
                hostname: CONFIG.server.host,
                port: CONFIG.server.port,
                path: '/user-service/user/login',
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Content-Length': Buffer.byteLength(postData)
                }
            };

            const req = http.request(options, (res) => {
                let data = '';
                res.on('data', (chunk) => {
                    data += chunk;
                });
                res.on('end', () => {
                    try {
                        const response = JSON.parse(data);
                        if (response.code === 0 && response.data && response.data.accessToken) {
                            this.token = response.data.accessToken;
                            this.userId = response.data.userId;
                            console.log('✅ HTTP登录成功');
                            console.log(`   用户ID: ${this.userId}`);
                            console.log(`   Token: ${this.token.substring(0, 20)}...`);
                            resolve(response);
                        } else {
                            console.error('❌ HTTP登录失败:', response);
                            reject(new Error(response.msg || '登录失败'));
                        }
                    } catch (error) {
                        console.error('❌ 解析登录响应失败:', error);
                        reject(error);
                    }
                });
            });

            req.on('error', (error) => {
                console.error('❌ HTTP请求失败:', error);
                reject(error);
            });

            req.write(postData);
            req.end();
        });
    }

    // WebSocket连接
    async connect() {
        console.log('🔌 建立WebSocket连接...');

        return new Promise((resolve, reject) => {
            this.ws = new WebSocket(`ws://localhost:3000/user-service/websocket?t=${this.token}`);

            this.ws.on('open', () => {
                console.log('✅ WebSocket连接成功');
                resolve();
            });

            this.ws.on('message', (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    this.handleWebSocketMessage(message);
                } catch (error) {
                    console.log('📨 收到原始消息:', data.toString());
                }
            });

            this.ws.on('error', (error) => {
                console.error('❌ WebSocket错误:', error);
                reject(error);
            });

            this.ws.on('close', () => {
                console.log('🔌 WebSocket连接关闭');
            });
        });
    }

    // 处理WebSocket消息
    handleWebSocketMessage(message) {
        console.log('📨 收到消息:', JSON.stringify(message, null, 2));

        // 处理角色列表响应
        if (message.act_id === 1008) {
            if (message.code === 0 && message.data && message.data.characters) {
                this.characters = message.data.characters;
                console.log(`📋 获取到 ${this.characters.length} 个角色`);
            }
        }

        // 处理角色选择响应
        if (message.act_id === 1009) {
            if (message.code === 0) {
                console.log('✅ 角色选择成功');
            }
        }
    }

    async sendMessage(message) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify(message));
            console.log('📤 发送消息:', JSON.stringify(message, null, 2));
        } else {
            console.error('❌ WebSocket未连接');
        }
    }

    // 查询角色列表
    async queryCharacters() {
        console.log('📋 查询角色列表...');
        await this.sendMessage({
            c: 1008,
            d: {
                token: this.token
            }
        });
        await this.delay(1000);
    }

    // 选择角色
    async selectCharacter() {
        console.log('👤 选择角色...');

        if (this.characters.length === 0) {
            console.log('❌ 没有可用角色');
            return;
        }

        // 选择第一个角色
        this.selectedCharacter = this.characters[0];
        console.log(`🎭 选择角色: ${this.selectedCharacter.name} (ID: ${this.selectedCharacter.id})`);

        await this.sendMessage({
            c: 1009,
            d: {
                roleId: this.selectedCharacter.id,
                token: this.token
            }
        });
        await this.delay(1000);
    }

    // 延迟函数
    delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    async testGemSystem() {
        console.log('\n🔮 开始测试宝石系统...\n');

        // 1. 测试查询宝石背包 (6034)
        console.log('1️⃣ 测试查询宝石背包 (6034)');
        await this.sendMessage({
            c: 6034,
            d: {
                pageNum: 0
            }
        });
        await this.delay(1000);

        // 2. 测试开矿生成宝石 (2032) - 原木宝盒
        console.log('\n2️⃣ 测试开矿生成宝石 (2032) - 原木宝盒');
        await this.sendMessage({
            c: 2032,
            d: {
                id: 154  // 原木宝盒
            }
        });
        await this.delay(1000);

        // 3. 再次查询宝石背包，查看是否生成了宝石
        console.log('\n3️⃣ 再次查询宝石背包，查看生成的宝石');
        await this.sendMessage({
            c: 6034,
            d: {
                pageNum: 0
            }
        });
        await this.delay(1000);

        // 4. 测试开矿生成宝石 (2032) - 精钢宝盒
        console.log('\n4️⃣ 测试开矿生成宝石 (2032) - 精钢宝盒');
        await this.sendMessage({
            c: 2032,
            d: {
                id: 155  // 精钢宝盒
            }
        });
        await this.delay(1000);

        // 5. 测试开矿生成宝石 (2032) - 珍奇宝盒
        console.log('\n5️⃣ 测试开矿生成宝石 (2032) - 珍奇宝盒');
        await this.sendMessage({
            c: 2032,
            d: {
                id: 156  // 珍奇宝盒
            }
        });
        await this.delay(1000);

        // 6. 最终查询宝石背包
        console.log('\n6️⃣ 最终查询宝石背包');
        await this.sendMessage({
            c: 6034,
            d: {
                pageNum: 0
            }
        });
        await this.delay(1000);

        // 7. 测试镶嵌宝石 (6035) - 假设有装备ID为1的武器
        console.log('\n7️⃣ 测试镶嵌宝石 (6035)');
        await this.sendMessage({
            c: 6035,
            d: {
                equipmentId: 1,
                equipmentType: 'weapon',
                socketSlot: 1,
                gemInventoryId: 1  // 假设宝石背包ID为1
            }
        });
        await this.delay(1000);

        // 8. 测试查询装备宝石信息 (6037)
        console.log('\n8️⃣ 测试查询装备宝石信息 (6037)');
        await this.sendMessage({
            c: 6037,
            d: {
                equipmentId: 1,
                equipmentType: 'weapon'
            }
        });
        await this.delay(1000);

        // 9. 测试卸下宝石 (6036)
        console.log('\n9️⃣ 测试卸下宝石 (6036)');
        await this.sendMessage({
            c: 6036,
            d: {
                equipmentId: 1,
                equipmentType: 'weapon',
                socketSlot: 1
            }
        });
        await this.delay(1000);

        console.log('\n✅ 宝石系统测试完成！');
    }

    async run() {
        try {
            console.log('🚀 开始宝石系统测试...\n');

            // 1. HTTP登录
            await this.httpLogin();

            // 2. 建立WebSocket连接
            await this.connect();

            // 3. 查询角色列表
            await this.queryCharacters();

            // 4. 选择角色
            await this.selectCharacter();

            // 5. 测试宝石系统
            await this.testGemSystem();

            // 保持连接一段时间以便查看结果
            await this.delay(5000);

            if (this.ws) {
                this.ws.close();
            }
        } catch (error) {
            console.error('❌ 测试失败:', error);
            if (this.ws) {
                this.ws.close();
            }
        }
    }
}

// 运行测试
const tester = new GemSystemTester();
tester.run().catch(console.error);
